import { memo, createContext, useMemo, useReducer, useState, useEffect, useContext } from 'react';
import { Link, Outlet } from 'umi';
import IndexStyle from './index.less';
import { Tabs, Button, Tag, App } from 'antd';
import { GlobalContext, initialState, emitter } from './context';
import { reducer } from './reducer';
import { useSelector } from './useSelector';
// import AppManager from '@/pages/AppManager';
import SideBar from '@/pages/SideBar';

function Provider({ children }){
  const [global, dispatch] = useReducer(reducer, initialState);
  useEffect(()=>{
    emitter.emit('stateChange', global);
  },[global]);
  useEffect(()=>{
    const handleResize = ()=>{
      dispatch({ type:'setWidth', payload:window.innerWidth });
    }
    window.addEventListener('resize', handleResize);
    return ()=>{
      window.removeEventListener('resize', handleResize);
    }
  },[])
  const store = useMemo(()=>({
    dispatch,
    getState:()=>global
  }),[]);
  return (
    <GlobalContext.Provider value={store}>
      { children }
    </GlobalContext.Provider>
  )
}

const Layout = ()=>{
  const [tabList] = useSelector(state=>state.tabList);
  const [currentTab] = useSelector(state=>state.currentTab);
  console.log('layout render...');
  return (
    <Tabs
        className={IndexStyle['flex-tabs']}
        tabBarStyle={{ paddingLeft:'2rem', marginBottom:'0' }}
        activeKey={currentTab}
        onChange={activeKey=>dispatch({ type:'setCurrentTab', payload:activeKey })}
        items={tabList.map(tab=>({
          ...tab,
          children:(
            currentTab === tab.key
            ?
            <div className={IndexStyle['content-container']}>
              <div className={IndexStyle['sidebar-container']}><SideBar /></div>
              <div className={IndexStyle['main-content']}>
                {/* {
                  currentTab === 'app' 
                  ?
                  <AppManager />
                  :
                  null
                } */}
              </div>
            </div>
            :
            null
          )
        }))}
      />
  )
}

export default function Main(){
  return (  
    <Provider>
      <Layout />
    </Provider>
  )
}




